package rpc;

import com.rabbitmq.client.*;
import com.rabbitmq.client.impl.AMQBasicProperties;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2025-04-01
 * Time: 16:20
 */
public class RpcClinet {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("1.95.194.117");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("wangkun");
        connectionFactory.setPassword("200411");
        connectionFactory.setVirtualHost("study");
        Connection connection = connectionFactory.newConnection();

        //2.通信
        Channel channel = connection.createChannel();

        //3.声明队列
        channel.queueDeclare("queue1",true,false,false,null);
        channel.queueDeclare("queue2",true,false,false,null);
        //4.发送请求
        //发送的消息内容
        String message = "hello RPC";

        //设置请求的唯一标识和相关属性
        String correlationID = UUID.randomUUID().toString();
        AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
                .replyTo(correlationID)
                .correlationId("queue1")
                .build();
        channel.basicPublish("","queue1",props,message.getBytes());

        //5.接收响应
        //使用阻塞队列来进行处理响应
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(1);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String responseMessage = new String(body);
                System.out.println("收到消息: " + responseMessage);
                if (correlationID.equals(properties.getCorrelationId())) {
                    //如果此时服务器返回来的响应的CorrelationID和客户端的相同，则加入阻塞队列中
                    blockingQueue.offer(responseMessage);
                }
            }
        };
        channel.basicConsume("queue2",true,defaultConsumer);
        String result = blockingQueue.take();
        System.out.println("响应结果: " + result);
    }
}
